<script setup lang="ts">
import { computed, nextTick, provide, reactive, ref, watch } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { useOrderedChildren, useUniAppSystemRectInfo } from '@tuniao/tnui-vue3-uniapp/hooks'

import TnTabbar from '@tuniao/tnui-vue3-uniapp/components/tabbar/src/tabbar.vue'
import TnTabbarItem from '@tuniao/tnui-vue3-uniapp/components/tabbar/src/tabbar-item.vue'
import TnIcon from '@tuniao/tnui-vue3-uniapp/components/icon/src/icon.vue'

import BasicPage from './sub-page/components/basic/basic.vue'
import Settings from './sub-page/components/settings/settings.vue'

import type { CSSProperties } from 'vue'
import type { IndexSubPageContext } from '@/tokens'

import { useWxShare } from '@/hooks'
import { useAppI18n } from '@/hooks/use-i18n'
import { indexPageContextKey } from '@/tokens'

import { navMiniProgram } from '@/utils'

// 微信分享
onShareAppMessage(() => ({}))
onShareTimeline(() => ({}))
useWxShare({
  imageUrl:
    'https://resource.tuniaokj.com/images/vue3/market/vue3-banner-min.jpg',
})

const {
  children: items,
  addChild: addItem,
  removeChild: removeItem,
} = useOrderedChildren<IndexSubPageContext>()

const { navBarInfo } = useUniAppSystemRectInfo()

// 国际化
const { t, toggleLanguage, getCurrentLanguageText } = useAppI18n()

// 系统信息响应式更新
const systemInfo = ref(uni.getSystemInfoSync())

// 监听系统信息变化
watch(() => navBarInfo, () => {
  systemInfo.value = uni.getSystemInfoSync()
}, { deep: true })

// 语言切换按钮位置计算
const languageButtonStyle = computed(() => {
  // 使用响应式系统信息
  const currentSystemInfo = systemInfo.value
  const isH5 = currentSystemInfo.uniPlatform === 'web'
  const isWechat = currentSystemInfo.uniPlatform === 'devtools' || currentSystemInfo.platform === 'ios' || currentSystemInfo.platform === 'android'
  // 基础安全距离
  const safeTop = currentSystemInfo.statusBarHeight || 0
  const buttonHeight = 54 // 按钮高度
  const buttonMargin = 15 // 按钮边距
  
  let topPosition = 0
  
  if (isH5) {
    // H5环境下的位置计算 - 确保不碰到顶部
    topPosition = Math.max(safeTop + buttonMargin + 20, 20);
	
  } else if (isWechat) {
    // 微信小程序环境下的位置计算
    const navHeight = navBarInfo.height || 44
    const statusHeight = navBarInfo.statusHeight || 0
    topPosition = statusHeight + (navHeight / 2) - (buttonHeight / 2)
  } else {
    // 其他小程序环境
    topPosition = safeTop + buttonMargin
  }
  
  return {
    position: 'fixed',
    left: '15rpx',
    top: `${topPosition}px`,
    transform: 'translateY(-50%)',
    zIndex: 1000
  }
})

// 底部导航栏数据
const tabbarData = computed(() => [
  { text: t('common.home'), icon: 'home-fill' },
  { text: t('common.mine'), icon: 'my-fill' }
])

// 导航切换事件
const onTabbarChange = (index: string | number) => {
  if (!pageStatus.value?.[index as number]) {
    pageStatus.value[index as number] = true
    nextTick(() => {
      items.value?.[index as number]?.onLoad?.()
    })
  }

  items.value?.[index as number]?.onShow?.()
}

// 记录每个子页面的状态
const pageStatus = ref(Array.from({ length: tabbarData.value.length }, () => false))

// 当前选中的子页面的索引
const currentTabbarIndex = ref<number>(-1)

// pageContainer的样式
const pageContainerStyle = computed<(index: number) => CSSProperties>(() => {
  return (index: number) => {
    const style: CSSProperties = {}

    if (index !== currentTabbarIndex.value) {
      style.display = 'none'
    }

    return style
  }
})

onLoad((options: any) => {
  // 获取当前进入的子页面的索引，默认显示首页（索引0）
  const index = Number(options?.index || 0)
  // 设置当前子页面的状态为true
  pageStatus.value[index] = true
  
  // 重新获取系统信息以确保位置计算正确
  systemInfo.value = uni.getSystemInfoSync()
  
  nextTick(() => {
    currentTabbarIndex.value = index
    setTimeout(() => {
      // 执行子页面的onLoad钩子
      items.value?.[index]?.onLoad?.()
    }, 50)
  })
})

provide(
  indexPageContextKey,
  reactive({
    items,
    addItem,
    removeItem,
  })
)
</script>

<template>
  <!-- 虚拟首页 -->
  <view class="page" style="direction: ltr;">
    <!-- 语言切换按钮 - 动态计算位置 -->
    <view 
      class="tn-navbar-back"
      :style="languageButtonStyle"
      @tap.stop="toggleLanguage"
    >
      <view class="tn-navbar-back__text">
        <TnIcon name="global" />
        <text class="tn-navbar-back__text__value">{{ getCurrentLanguageText }}</text>
      </view>
    </view>

    <view
      v-if="pageStatus[0]"
      class="page__container"
      :style="pageContainerStyle(0)"
    >
      <scroll-view class="scroll-view" scroll-y>
		<BasicPage />
      </scroll-view>
    </view>
	<view
	  v-if="pageStatus[1]"
	  class="page__container"
	  :style="pageContainerStyle(1)"
	>
	  <scroll-view class="scroll-view" scroll-y>
	    <Settings />
	  </scroll-view>
	</view>
  </view>
  <TnTabbar
    v-model="currentTabbarIndex"
    fixed
    :placeholder="false"
    switch-animation
    frosted
    @change="onTabbarChange"
  >
    <TnTabbarItem
      v-for="(item, index) in tabbarData"
      :key="index"
      :name="index"
      :text="item.text"
      inactive-color="#c5cad5"
      :icon="item.icon"
      :active-icon="item.icon"
    />
  </TnTabbar>
</template>

<style lang="scss" scoped>

.page {
  position: relative;
  width: 100%;
  height: 100vh;

  &__container {
    position: relative;
    width: 100%;
    height: 100%;

    .scroll-view {
      width: 100%;
      height: 100%;
    }
  }
}



/* 语言切换按钮样式 - 基于图鸟UI navbar返回按钮样式 */
.tn-navbar-back {
  position: absolute;
  left: 15rpx;
  top: 50%;
  transform: translateY(-50%);



  /* 返回文字样式 */
  &__text {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    font-size: 30rpx;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.15);
    border: 1rpx solid rgba(255, 255, 255, 0.4);
    border-radius: 1000rpx;
    padding: 16rpx 24rpx;
    backdrop-filter: blur(20rpx);
    -webkit-backdrop-filter: blur(20rpx);
    transition: all 0.3s ease;

    &__value {
      margin-left: 8rpx;
      font-size: 24rpx;
      font-weight: 500;
    }
  }



  /* 点击效果 */
  &:active {
    .tn-navbar-back__text {
      background-color: rgba(0, 0, 0, 0.25);
      transform: scale(0.95);
    }
  }
}

</style>
